// ignore_for_file: unnecessary_overrides, non_constant_identifier_names

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:verse_systems/commom/models/aboutus_model.dart';
import 'package:verse_systems/commom/models/language_model.dart';
import 'package:verse_systems/commom/models/question_model.dart';
import 'package:verse_systems/commom/models/vipinfo_mode.dart';
import 'package:verse_systems/commom/routers/navigator_utils.dart';
import 'package:verse_systems/commom/routers/routes_pages_name.dart';
import 'package:verse_systems/net/http_dio.dart';
import 'package:verse_systems/net/src/sparrow_dio_config.dart';
import 'package:verse_systems/pages/home/home_control.dart';
import 'package:verse_systems/pages/mine/mine_state.dart';
import 'package:verse_systems/utils/account_util.dart';
import 'package:verse_systems/utils/loading.dart';
import 'package:verse_systems/widgets/alert.dart';

class MineControl extends GetxController {
  final MineState state = MineState();
  final home_control = Get.find<HomeControl>();

  updateRefresh(int index, bool value) {
    final List<QuestionModel> tem = state.tasksVoList;
    QuestionModel model = tem[index];
    model.isExpand = !model.isExpand;
    state.tasksVoList = tem;
    update();
  }

  getQuestion() async {
    final String token = await AccountUtil.getUserToken();
    Request.postCallback(
      HttpUrls.getQuestion,
      data: {'token': token},
      success: (res) async {
        ResultData result = ResultData.fromJson(res.data);
        if (result.status == 0) {
          debugPrint("getQuestion ----->$result");
          final List content = result.data["content"];
          state.tasksVoList =
              content.map((json) => QuestionModel.fromJson(json)).toList();
          update();
        }
      },
    );
  }

  onTapCard(int index) {
    debugPrint("---------$index-------");
    switch (index) {
      case 0: //我的订单
        Get.toNamed(RoutesPage.OrderPage);
        break;
      case 1: //我的抽奖
        Get.toNamed(RoutesPage.LuckyWheel);
        break;
      case 2: //关于我们
        Get.toNamed(RoutesPage.AboutUs);
        break;
      case 3: //常见问题
        Get.toNamed(RoutesPage.MieQuestion);
        break;
      case 4: //账号注销
        Get.toNamed(RoutesPage.MieLogOff);
        break;
      case 5: //注销账号
        Alert.showChoicelogoOffSheet(
            onPressed: onTapLogOff,
            hotline: state.hotline,
            work_hour: state.work_hour);
        break;

      default:
    }
  }

  onTapVip() {
    debugPrint("---------onTapVip-------");
    Get.toNamed(RoutesPage.MieVIP);
  }

  onTapLogOff() async {
    await launchUrl(Uri.parse("tel://${state.hotline}"));
  }

  logOut() async {
    Loading.show("loading".tr);
    final String token = await AccountUtil.getUserToken();
    Request.postCallback(
      HttpUrls.logOutUrl,
      data: {'token': token},
      success: (res) async {
        ResultData result = ResultData.fromJson(res.data);
        if (result.status == 0) {
          final clearAll = await AccountUtil.clearAll();
          if (clearAll) {
            Future.delayed(const Duration(milliseconds: 100), () {
              Loading.dismiss();
              NavigatorUtils.goToChangeHome();
              Get.offAllNamed(RoutesPage.Login);
            });
          }
        }
      },
      error: (p0) {
        Loading.dismiss();
      },
    );
  }

  onTapLogOut() {
    Alert.showAlert(
        title: "tips".tr,
        confirm: "quit".tr,
        cancel: "cancel".tr,
        content: "confirm_exit".tr,
        onPressed: logOut);
  }

  onTapContact() {
    NavigatorUtils.goToChangeContact();
  }

  onTapCertification() {
    if (state.agreementIsChecked) {
      home_control.jumpToAuthen();
    }
  }

  getVIPInfo() async {
    final String token = await AccountUtil.getUserToken();
    Request.postCallback(
      HttpUrls.getVIPInfo,
      data: {'token': token},
      success: (res) async {
        ResultData result = ResultData.fromJson(res.data);
        if (result.status == 0) {
          debugPrint("result----$result");
          final Map<String, dynamic> json = result.data;
          state.vipInfo = VipInfoModel.fromJson(json);
          update();
        }
      },
    );
  }

  getHotline() async {
    final String token = await AccountUtil.getUserToken();
    Request.postCallback(
      HttpUrls.getHotline,
      data: {'token': token},
      success: (res) async {
        ResultData result = ResultData.fromJson(res.data);
        if (result.status == 0) {
          state.hotline = result.data["hotline"];
          state.work_hour = result.data["work_hour"];
        }
      },
    );
  }

  getAboutInfo() async {
    final String token = await AccountUtil.getUserToken();
    Request.postCallback(
      HttpUrls.getAboutInfo,
      data: {'token': token},
      success: (res) async {
        ResultData result = ResultData.fromJson(res.data);
        if (result.status == 0) {
          debugPrint("getAboutInfo ----->$result");
          List content = result.data["content"];

          state.content =
              content.map((json) => AboutUsModel.fromJson(json)).toList();
          update();
        }
      },
    );
  }

  getUserInfo() async {
    final String token = await AccountUtil.getUserToken();
    Request.postCallback(
      HttpUrls.getUserInfo,
      data: {'token': token},
      success: (res) async {
        ResultData result = ResultData.fromJson(res.data);
        if (result.status == 0) {
          debugPrint("getUserInfo ----->$result");
          state.info = result.data;
          update();
        }
      },
    );
  }

  getLanguagesInfo() {
    List language = [
      {
        "language": "简体中文",
        "language_chosen": "false",
        "languageCode": "zh-CN",
        "languageTag": "CN"
      },
      {
        "language": "繁体中文",
        "language_chosen": "false",
        "languageCode": "zh-TW",
        "languageTag": "TW"
      }
    ];

    String languageCode = Get.locale!.toLanguageTag();
    debugPrint("cl-----$languageCode"); 
    for (var element in language) {
         if (element["languageCode"] == languageCode) {
            element["language_chosen"] = "true";
         } 
    }
    state.language = language.map((json) => LanguageModel.fromJson(json)).toList();
  }


  saveLanguage() async {
    final List results = state.language
        .where((model) => model.language_chosen == "true")
        .toList();
    if (results.isNotEmpty) {
      LanguageModel model = results.first;
      String languageCode = Get.locale!.toLanguageTag();
      if (languageCode == model.languageCode) {
        debugPrint("不用保存");
      } else {
        final String languageTag  =  model.languageTag.toString();
        await Get.updateLocale(Locale('zh', languageTag));
        await AccountUtil.setAppLanguages(languageTag);
        SparrowDioConfig.setLanguage("zh_${languageTag.toLowerCase()}");
        Get.back();
      }
    }
  }

  //单选逻辑
  checkLanguage({required int index}) {
    final List<LanguageModel> tem = state.language;
    LanguageModel model = tem[index];
    for (var element in tem) {
      if (model == element) {
        element.language_chosen = "true";
      } else {
        element.language_chosen = "false";
      }
    }
    state.language = tem;
    update();
  }

  @override
  void onInit() {
    super.onInit();
    getUserInfo();
  }
}
